﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Net;
using System.IO;
using Bingosoft.Common.Logging;
using HHMMS.FileServer;

namespace HHMMS.UI.Common
{
    /// <summary>
    /// 实现一个HTTP处理程序，用于在web应用程序中下载文件服务器上的文件
    /// 需在web应用程序中的web.config中增加相应的配置。
    /// </summary>
	public class DownloadHandler : IHttpHandler
	{
		// Fields
		private static readonly ILog log = LogManager.GetCurrentClassLogger();

		// Methods
        public void ProcessRequest(HttpContext context)
        {
            //真实文件名
            string fileName = context.Request.QueryString["name"];

            //文件服务器上的文件路径
            string filePath = context.Request.QueryString["path"];

            //文件真实下载地址
            string fileUrl = string.Format("{0}/download.ashx?path={1}&name={2}", FileServerSection.Current.Url.TrimEnd('/'), HttpUtility.UrlEncode(filePath), HttpUtility.UrlEncode(fileName));

            try
            {
                //初始化下载请求对象
                HttpWebRequest request = WebRequest.Create(fileUrl) as HttpWebRequest;
                if (FileServerSection.Current.UseDefaultCredential)
                {
                    request.Credentials = CredentialCache.DefaultCredentials;
                }
                else
                {
                    ICredentials credentials = new NetworkCredential(FileServerSection.Current.UserName, FileServerSection.Current.Password);
                    request.Credentials = credentials;
                }

                //获取请求的响应并输出到客户端
                using (HttpWebResponse response = request.GetResponse() as HttpWebResponse)
                {
                    context.Response.Clear();
                    context.Response.Buffer = true;
                    context.Response.ContentType = response.ContentType;
                    context.Response.AddHeader("Content-Disposition", "attachment;filename=" + context.Server.UrlPathEncode(fileName));
                    using (Stream stream = response.GetResponseStream())
                    {
                        int count = 0;
                        byte[] buffer = new byte[FileServerSection.Current.BlockSize];
                        while ((count = stream.Read(buffer, 0, buffer.Length)) > 0)
                        {
                            context.Response.OutputStream.Write(buffer, 0, count);
                            context.Response.Flush(); 
                        }
                    }
                }
            }
            catch (Exception ex)
            {
                log.Error(fileUrl + " 下载文件错误！", ex);
                context.Response.Clear();
                context.Response.Write(ex.Message);
                context.Response.End();
            }
        }

		// Properties
		public bool IsReusable
		{
			get
			{
				return true;
			}
		}
	}
}
